package com.keyin.protocol;

import java.io.ByteArrayOutputStream;
import java.util.ArrayList;
import java.util.HashMap;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.BitmapFactory.Options;
import android.os.Handler;
import android.os.Looper;
import android.util.Log;
import android.widget.Toast;

import com.keyin.App;
import com.keyin.android.cache.FileDiskCache;
import com.keyin.android.net.Callback;
import com.keyin.android.net.Http;
import com.keyin.android.net.Param;

public class DownloadMagazine {

	private int index = 1;

	private static HashMap<String, ArrayList<Object>> penddingBitmaps = new HashMap<String, ArrayList<Object>>();

	private Periodical magazine;
	private Context context;

	private FileDiskCache cache;

	public DownloadMagazine(Context c, Periodical magazine) {
		context = c;
		this.magazine = magazine;
		cache = new FileDiskCache(App.root);
		
		Periodical periodical = MagazineIndexCache.get(magazine.periodical_id);
		if (periodical != null){
			Intent i = new Intent(context, com.keyin.CatalogActivity.class);
			i.putExtra("peridocal_id", magazine.periodical_id);
			context.startActivity(i);
			
			return;
		}

		handler.sendEmptyMessage(0);
	}

	private void start() {
		
		// write the index file
		MagazineIndexCache.put(magazine);

		Protocol p = ProtocolHelper.getPeriodical(context,
				magazine.periodical_id, index);

		final String url = p.getUrl();
		Log.d("Download !!!", magazine.toString());
		Log.d("Download !!!", url);

		PeriodicalImageProtocol protocol = new PeriodicalImageProtocol(context,
				url);
		protocol.startTrans(new PeriodicalImageProtocol.Reciever() {
			@Override
			public void onRecieve(byte[] data) {
				// 生成所略图
				Bitmap bm = null;
				Options op = new Options();
				op.inSampleSize = 6;
				op.inJustDecodeBounds = false;
				bm = BitmapFactory.decodeByteArray(data, 0, data.length, op);

				ByteArrayOutputStream baos = new ByteArrayOutputStream();
				bm.compress(Bitmap.CompressFormat.JPEG, 100, baos);
				byte[] thumbData = baos.toByteArray();

				FileDiskCache imgCache = new FileDiskCache(App.root);
				imgCache.put("thumb_" + CacheImageProtocol.encode(url),
						thumbData);

				if (index < magazine.pages) {
					index++;
					handler.sendEmptyMessage(1);
				}
			}
		});
	}

	private Handler handler = new Handler() {
		public void handleMessage(android.os.Message msg) {
			if (msg.what == 0) {
				Toast.makeText(context, "开始下载", Toast.LENGTH_SHORT).show();
				start();
			} else if (msg.what == 1) {
				Toast.makeText(context, "开始下载" + index + "页",
						Toast.LENGTH_SHORT).show();
				start();
			}
		};
	};

	private class MagazineCallback extends Callback {
		private String url;

		public MagazineCallback(String periodicalId, int index) {
			if (periodicalId == null) {
				periodicalId = "495772";
			}
			// http://www.keyin.cn/ipad/get_magazine.php?periodical_id=495772&page=1
			final String host = "http://www.keyin.cn/ipad/get_magazine.php?";

			Param p = new Param();
			p.append("periodical_id", periodicalId);
			p.append("page", String.valueOf(index));

			url = host.concat(p.toString());
		}

		@Override
		public void onRecieve(byte[] data) {
			index++;
			// if (index >= magazine.pages){
			// Toast.makeText(context, "下载完毕", Toast.LENGTH_SHORT).show();
			// return;
			// }
			Looper.prepare();
			Toast.makeText(context, "开始下载" + index + "页", Toast.LENGTH_SHORT)
					.show();
			Looper.loop();

			Http http = new Http(new MagazineCallback(magazine.periodical_id,
					index));
			http.start();
		}

		@Override
		public void onException(Exception e) {
			Toast.makeText(context, "下载完毕", Toast.LENGTH_SHORT).show();
		}

		@Override
		public String getUrl() {
			return url;
		}

		@Override
		public byte[] getPostParam() {
			return null;
		}

		@Override
		public Param getHeader() {
			return null;
		}

		@Override
		public Context getContext() {
			return context;
		}
	};
}
